package com.gobang.util;

import com.gobang.model.Chessboard;

public class PCPlayer {
	private int color;
	private int[][] chessboard;
	private int[][][] pcContext;
	private int[][][] playerContext;
	private Chessboard cbd;
	
	public PCPlayer(int color, int[][] chessboard, Chessboard cbd){
		this.cbd = cbd;
		this.color = color;
		this.chessboard = chessboard;
		int size = chessboard.length;
		pcContext = new int[size][size][4];
		playerContext = new int[size][size][4];
	}
	
	public int putPiece(){
		initContext();
		int[] pos = getPos();
		return cbd.putChess(color, pos[0], pos[1]);
	}
	
	private void initContext(){
		int otherColor = getOtherColor(color);
		for(int i = 0; i <= Chessboard.GRID_NUM; i++){
			for(int j=0; j <= Chessboard.GRID_NUM; j++){
				if(chessboard[i][j] == 0){
					initOnePosContext(i, j , color);
					initOnePosContext(i, j, otherColor);
				} else {
					for(int k = 0 ; k < 4 ; k++){
						pcContext[i][j][k] = 0;
						playerContext[i][j][k] = 0;
					}
				}
			}
		}
	}
	
	private int getOtherColor(int color){
		if(color == Chessboard.PIECE_BLACK){
			return Chessboard.PIECE_WHITE;
		} else {
			return Chessboard.PIECE_BLACK;
		}
	}
	
	private void initOnePosContext(int x, int y, int color){
		//向左、向右、向上、向下、左上、右上、右下、左下
		int[][] moves = new int[][]{{-1, 0},{1, 0},{0,-1},{0, 1},
									{-1,-1},{1, 1},{1,-1},{-1,1}};
		
		int num = 1;
		int k = 0;
		for (int i = 0; i < moves.length; i = i + 2) {
			num = 1;
			
			int nx = x + moves[i][0];
			int ny = y + moves[i][1];
			while (nx >= 0 && nx <= Chessboard.GRID_NUM && ny >= 0 && ny <= Chessboard.GRID_NUM + 1) {
				if (chessboard[nx][ny] == color) {
					num++;
				} else {
					break;
				}
				nx += moves[i][0];
				ny += moves[i][1];
			}

			nx = x + moves[i + 1][0];
			ny = y + moves[i + 1][1];
			while (nx >= 0 && nx <= Chessboard.GRID_NUM && ny >= 0 && ny <= Chessboard.GRID_NUM) {
				if (chessboard[nx][ny] == color) {
					num++;
				} else {
					break;
				}
				nx += moves[i + 1][0];
				ny += moves[i + 1][1];
			}
			
			if(color == this.color){//0 2 3 6
				pcContext[x][y][k] = num;
			} else {
				playerContext[x][y][k] = num;
			}
			k++;
		}
	}
	
	private int[] getPos(){
		int[] pos = new int[2];
		int size = chessboard.length;
		
		int max = 0;
		for(int i = 0; i < size; i++){
			for(int j = 0; j < size; j++){
				for(int k = 0; k < 4 ; k++){
					if(pcContext[i][j][k] > max){
						max = pcContext[i][j][k];
						pos[0] = i;
						pos[1] = j;
					}
					if(playerContext[i][j][k] > max){
						max = playerContext[i][j][k];
						pos[0] = i;
						pos[1] = j;
					}
				}
			}
		}
		
		return pos;
	}

}
